<?php
/**
 * PddFilter.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/12/29- 上午10:27
 */

namespace common\jobs\copy\tools;

use common\exception\JumpException;
use common\jobs\dao\PddCopyProductsDao;
use common\exception\CopyException;
use common\jobs\models\PddFilterTpl;
use common\constants\PlatformConst;
use common\helpers\StringHelper;
use common\models\com\ComSpider;
use yii\helpers\ArrayHelper;

/**
 * 复制过程中跳过属性匹配
 * Class PddFilter
 * @package api\task\tools
 */
class PddFilterJump
{


    /**
     * 源数据
     * @var ComSpider
     */
    public $sourceData = null;


    protected $mall_id;


    protected $uid;


    /**
     * 过滤规则信息
     * @var PddFilterTpl
     */
    public $filter = null;


    public function __construct(ComSpider $sourceData,PddFilterTpl $filter,int $mall_id,int $uid)
    {
        $this->sourceData = $sourceData;
        $this->filter = $filter;
        $this->mall_id = $mall_id;
        $this->uid = $uid;
    }

    /**
     * 全局设置
     * @throws JumpException
     */
    public function globalSetting()
    {

        // {id:1,name:'跳过已复制商品'},
        //        {id:2,name:'跳过授权店铺已复制'},
        //        {id:3,name:'跳过不包邮商品'},
        //        {id:4,name:'跳过无颜色图SKU'},
        //        {id:5,name:'跳过已下架的商品'},
        //        {id:6,name:'跳过有品牌的商品'},
        //        {id:7,name:'跳过3C商品'},
        //        {id:8,name:'跳过海外/代购商品'},
        //        {id:9,name:'跳过二手商品'},
        //        {id:10,name:'跳过天猫/京东超市'},
        //        {id:11,name:'跳过天猫/淘宝限购商品'},
        //        {id:12,name:'跳过全英文标题商品'},
        $copyProduct = new PddCopyProductsDao();
        //跳过已复制商品
        if($this->_checkSetBasicJump(1)){
            $isCopy = $copyProduct->getInfoByNumIIdAndMallId($this->sourceData->plat_id,$this->mall_id);
            if($isCopy)
            {
                throw new JumpException('上货配置设置了【跳过已复制商品】当前商品已复制，请查看复制记录id:'.$isCopy->id);
            }
        }
        //跳过授权店已复制
        if($this->_checkSetBasicJump(2))
        {
            $isAllCopy = $copyProduct->getInfoByStatusAndUidAndNumIId($this->sourceData->plat_id,$this->uid);
            if($isAllCopy)
            {
                throw new JumpException('上货配置设置了【跳过授权店铺已复制】当前商品授权店已复制，请查看复制记录id:'.$isAllCopy->id);
            }
        }
        $extendData = $this->sourceData->extend_data['extend_data'];
        //有邮费的商品跳过
        if($this->_checkSetBasicJump(3))
        {
            if((isset($extendData['post_fee']) && $extendData['post_fee'] > 0) ||
                (isset($extendData['express_fee']) && $extendData['express_fee'] > 0))
            {
                throw new JumpException('上货配置设置了【跳过不包邮商品】');
            }
        }

        //跳过无颜色图SKU
        if($this->_checkSetBasicJump(4))
        {
            if(is_array($this->sourceData->extend_data['sku_img']) && count($this->sourceData->extend_data['sku_img']) == 0)
            {
                throw new JumpException('上货配置设置了【跳过无颜色图SKU】');
            }
        }


        //跳过有品牌的商品
        if($this->_checkSetBasicJump(6))
        {
            if(isset($this->sourceData->extend_data['attr']) && is_array($this->sourceData->extend_data['attr']))
            {
                $tmpAttr = ArrayHelper::getColumn($this->sourceData->extend_data['attr'],'key');

                if(in_array('品牌',$tmpAttr))
                {
                    throw new JumpException('上货配置设置了【跳过有品牌的商品】');
                }
            }
        }

        //跳过3C商品
        if($this->_checkSetBasicJump(7))
        {
            if(isset($this->sourceData->extend_data['attr']) && is_array($this->sourceData->extend_data['attr']))
            {
                $tmpAttr = ArrayHelper::getColumn($this->sourceData->extend_data['attr'],'key');
                foreach($tmpAttr as $item)
                {
                    if(strpos($item,'3C') !== false)
                    {
                        throw new JumpException('上货配置设置了【跳过3C商品】');
                    }
                }
            }
        }
        //跳过二手商品
        if($this->_checkSetBasicJump(9))
        {
            if(isset($this->sourceData->extend_data['title']) && !empty($this->sourceData->extend_data['title']))
            {
                if(strpos($this->sourceData->extend_data['title'],'二手') !== false)
                {
                    throw new JumpException('上货配置设置了【跳过二手商品】');
                }
            }
        }
        //跳过天猫/京东超市
        if($this->_checkSetBasicJump(10))
        {
            if(in_array($this->sourceData->platform,[PlatformConst::PLATFORM_TMALL,PlatformConst::PLATFORM_JD]))
            {
                throw new JumpException('上货配置设置了【跳过天猫/京东超市】');
            }
        }
        //跳过全英文标题商品
        if($this->_checkSetBasicJump(12))
        {
            if(isset($this->sourceData->extend_data['title']) && !empty($this->sourceData->extend_data['title']))
            {
                if(StringHelper::checkStrIsYw($this->sourceData->extend_data['title']))
                {
                    throw new JumpException('上货配置设置了【跳过全英文标题商品】');
                }
            }
        }

    }


    /**
     * 重复跳过
     * @throws JumpException
     */
    public function jumpRepeat()
    {
        $seasonSetting = @$this->filter->settings['jump']['jump_repeat']['season'];
        if(isset($seasonSetting) && is_array($seasonSetting) && count($seasonSetting))
        {
            // {id:1,name:'春'},
            //        {id:2,name:'夏'},
            //        {id:3,name:'秋'},
            //        {id:4,name:'冬'},
            foreach($seasonSetting as $item)
            {
                switch ($item)
                {
                    case 1:
                        if(strpos($this->sourceData->extend_data['title'],'春季') !== false)
                        {
                            throw new JumpException('上货配置设置了【跳过季节商品】，命中春季');
                        }
                        break;
                    case 2:
                        if(strpos($this->sourceData->extend_data['title'],'夏季') !== false)
                        {
                            throw new JumpException('上货配置设置了【跳过季节商品】，命中夏季');
                        }
                        break;
                    case 3:
                        if(strpos($this->sourceData->extend_data['title'],'秋季') !== false)
                        {
                            throw new JumpException('上货配置设置了【跳过季节商品】，命中秋季');
                        }
                        break;
                    case 4:
                        if(strpos($this->sourceData->extend_data['title'],'冬季') !== false)
                        {
                            throw new JumpException('上货配置设置了【跳过季节商品】，命中冬季');
                        }
                        break;
                }
            }
        }
    }


    /**
     * 跳过设置的阀值
     * @throws JumpException
     */
    public function jumpThreshold()
    {

        //拿到跳过的配置信息
        $setting = $this->filter->settings['jump'];
        $skuList = @$this->sourceData->extend_data['skus'];

        if(!is_array($skuList))
        {
            throw new JumpException('sku信息不完整');
        }


        //没有sku，单品 不需要对价格做判断了
        if(count($skuList) == 0)
        {
            return true;
        }else{
            //销售价
            $prices = ArrayHelper::getColumn($skuList,'sale_price');

            //库存列表
            $stockList = ArrayHelper::getColumn($skuList,'stock');
            $minPrices = min($prices);
            $maxPrices = max($prices);
        }


        //跳过总库存
        if(isset($setting['jump_stock']) && !empty($setting['jump_stock']))
        {
            $totalStock = array_sum($stockList);
            if($totalStock < intval($setting['jump_stock']))
            {
                throw new JumpException('上货配置设置了【跳过库存】，当前商品库存为:'.$totalStock.'小于:'.$setting['jump_stock']);
            }
        }
        //跳过销量
        if(isset($setting['jump_sell']) && !empty($setting['jump_sell']))
        {
            $sales = @$this->sourceData->extend_data['extend_data']['sales'];

            if(isset($sales)  && intval($sales) < intval($setting['jump_sell']))
            {
                throw new JumpException('上货配置设置了【跳过销量】，当前商品销量为:'.$sales.'小于:'.$setting['jump_sell']);
            }
        }


        //跳过价格-最小值
        if(isset($setting['jump_price']['min']) && !empty($setting['jump_price']['min']))
        {
            $settingMin = (float)$setting['jump_price']['min'];
            if($minPrices <= $settingMin)
            {
                throw new JumpException('上货配置设置了【跳过价格】，当前商品最小售价为:'.$minPrices.'小于:'.$settingMin);
            }
        }
        //跳过价格-最大值
        if(isset($setting['jump_price']['max']) && !empty($setting['jump_price']['max']))
        {
            $settingMax = (float)$setting['jump_price']['max'];
            if($maxPrices >= $settingMax)
            {
                throw new JumpException('上货配置设置了【跳过价格】，当前商品最大售价为:'.$maxPrices.'大于:'.$settingMax);
            }
        }

        //跳过sku价格差-差值比较
        $diffRes =  $multipleRes = false;
        $diffPrice = $maxPrices - $minPrices;
        $multiplePrice = ceil($maxPrices/$minPrices);
        if(isset($setting['jump_sku']['diff']) && !empty($setting['jump_sku']['diff']))
        {
            $settingMax = (float)$setting['jump_sku']['diff'];


            if($diffPrice >= $settingMax)
            {
                $diffRes = true;
            }
        }

        //跳过sku价格差-倍数比较
        if(isset($setting['jump_sku']['multiple']) && !empty($setting['jump_sku']['multiple']))
        {
            $settingMultiple = intval($setting['jump_sku']['diff']);

            if($multiplePrice >= $settingMultiple)
            {
                $multipleRes = true;
            }
        }
        //1=>并且 2=》或者
        $isAnd = isset($setting['jump_sku']['and']) && $setting['jump_sku']['and'] == 1 ? true : false;
        if($isAnd)
        {
            if($diffRes && $multipleRes)
            {
                throw new JumpException('上货配置设置了【跳过sku价差】，当前商品SKU价格差值:'.$diffPrice.'并且差值倍数大于:'.$multiplePrice);
            }
        }else{
            if($diffRes || $multipleRes)
            {
                throw new JumpException('上货配置设置了【跳过sku价差】，当前商品SKU价格差值:'.$diffPrice.'或者差值倍数大于:'.$multiplePrice);
            }
        }

        //跳过标题字数
        if(isset($setting['jump_title_num']) && !empty($setting['jump_title_num']))
        {
            $titleLen = StringHelper::calLenByGBK($this->sourceData->extend_data['title']);

            $settingTitleNum = intval($setting['jump_title_num']);
            if($titleLen < $settingTitleNum)
            {
                throw new JumpException('上货配置设置了【跳过跳过标题字数】，当前商品标题字数为:'.$titleLen.'低于设置的:'.$settingTitleNum);
            }
        }

        $mobileDetailNum = isset($setting['jump_pic_num']['mobile_num']) ? intval($setting['jump_pic_num']['mobile_num']) : 0;
        $pcDetailNum = isset($setting['jump_pic_num']['pc_num']) ? intval($setting['jump_pic_num']['pc_num']) : 0;
        //跳过详情图数
        $detailGallery = @$this->sourceData->extend_data['detail_gallery'];
        if(isset($detailGallery) && is_array($detailGallery))
        {
            $detailImagesNum = count($detailGallery);
            if($mobileDetailNum > $detailImagesNum)
            {
                throw new JumpException('上货配置设置了【跳过详情图数】，当前商品详情图为:'.$detailImagesNum.'低于设置的:'.$mobileDetailNum);
            }

            if($pcDetailNum > $detailImagesNum)
            {
                throw new JumpException('上货配置设置了【跳过详情图数】，当前商品详情图为:'.$detailImagesNum.'低于设置的:'.$pcDetailNum);
            }
        }

        //跳过标题关键字
        if(isset($setting['jump_keywords_title']) && !empty($setting['jump_keywords_title']))
        {
            $titleKeywords = explode(',',$setting['jump_keywords_title']);
            if(count($titleKeywords))
            {
                foreach ($titleKeywords as $keyword)
                {
                    if(strpos($this->sourceData->extend_data['title'],$keyword) !== false)
                    {
                        throw new JumpException('上货配置设置了【跳过标题关键字】，当前商品标题命中:'.$keyword.'关键词');

                    }
                }
            }
        }

        //跳过sku关键词
        if(isset($setting['jump_keywords_sku']) && !empty($setting['jump_keywords_sku']))
        {
            $skuKeywords = explode(',',$setting['jump_keywords_sku']);
            if(count($skuKeywords))
            {
                $skuValueArr = [];
                foreach ($skuList as $s => $sku)
                {
                    $properties_name = $sku['properties_name'] ?  StringHelper::jsonDecode($sku['properties_name']) : [];
                    if(count($properties_name))
                    {
                        foreach ($properties_name as $name)
                        {
                            list($skuKey,$skuValue) = explode(":", $name);

                            array_push($skuValueArr,$skuValue);
                        }
                    }
                }
                $skuValueArr = array_unique($skuValueArr);
                foreach ($skuKeywords as $keyword)
                {
                    if(in_array($keyword,$skuValueArr) !== false)
                    {
                        throw new JumpException('上货配置设置了【跳过sku关键词】，当前sku值中命中:'.$keyword.'关键词');
                    }
                }
            }
        }



        //跳过品牌关键字
        if(isset($setting['jump_keywords_brand']) && !empty($setting['jump_keywords_brand']))
        {
            $brandsKeywords = explode(',',$setting['jump_keywords_brand']);
            if(count($brandsKeywords))
            {
                if(isset($this->sourceData->extend_data['attr']) && is_array($this->sourceData->extend_data['attr']))
                {
                    $attrMap = ArrayHelper::map($this->sourceData->extend_data['attr'],'key','value');

                    $brandValue = isset($attrMap['品牌']) ? trim($attrMap['品牌']) : null;

                    if($brandValue)
                    {
                        foreach ($brandsKeywords as $keyword)
                        {
                            if(strpos($brandValue,$keyword) !== false)
                            {
                                throw new JumpException('上货配置设置了【跳过品牌关键字】，当前品牌值为:'.$brandValue.',命中关键词:'.$keyword);
                            }
                        }
                    }
                }

            }
        }
    }

    //检测是否在全局配置里面
    private function _checkSetBasicJump(int $basicId)
    {
        if(isset($this->filter->settings['jump']['jump_basic']) && is_array($this->filter->settings['jump']['jump_basic'])
            && in_array($basicId,$this->filter->settings['jump']['jump_basic']))
        {
            return true;
        }
        return false;
    }

}